package com.wnzt.baszh.util.common;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;



public class GlobalFun {

	protected static java.text.DecimalFormat df = new java.text.DecimalFormat(
			"#.##");
	protected static Logger logger = Logger.getLogger(GlobalFun.class);

	private static final NumberFormat numberFormater = NumberFormat
			.getNumberInstance();

	public static String getErrCauseMsg(Exception e, Class errCls) {
		if (e == null)
			return "";
		Throwable e1 = (Throwable) e.getCause();
		if (e1 == null)
			return e.getMessage();
		return e1.getMessage();
	}

	public static String getErrCauseMsg(Exception e) {
		if (e == null)
			return "";
		Throwable e1 = (Throwable) e.getCause();
		if (e1 == null)
			return e.getMessage();
		return e1.getMessage();
	}

	/**
	 * 
	 * 判断传入参数是否有效
	 */
	public static boolean hasValue(String s) {
		return ((s != null) && (s.trim().length() > 0) && !StringUtils.isBlank(s));
	}

	public static boolean hasValue(Object obj) {
		return (obj != null);
	}
	
	public static boolean hasValue(Integer i) {
		return i!=null;
//		return ((i != null) && (i.intValue() > 0));
	}

	public static boolean hasValue(Long i) {
		return ((i != null) && (i.intValue() > 0));
	}

	public static boolean hasValue(Double i) {
		return ((i != null) && (i.doubleValue() > 0));
	}
    /**
     * 获取参数验证后的值
     */
	public static String getHasValue(String s) {
		if(s==null||"".equals(s.trim())||"null".equals(s.trim())){ //如果为""是也赋值为null
			return null;
		}else {
			return s.trim(); //过滤空格
		}
	}
	


	/**
	 * @param file
	 * @return
	 * @throws IOException
	 *             File转换到byte[]
	 */
	public static byte[] fileToByte(File file) throws IOException {
		byte[] bytes = null;
		if (file != null) {
			bytes = FileCopyUtils.copyToByteArray(file);
		}
		return bytes;
	}

	/**
	 * @param btyes
	 * @param file
	 * @throws IOException
	 *             byte[]转换到File
	 */
	public static void byteToFile(byte[] btyes, File file) throws IOException {
		if (file != null) {
			if (!file.exists()) {
				file.createNewFile();
			}
			FileCopyUtils.copy(btyes, file);
		}
	}

	/**
	 * 验证是否为Integer
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateInteger(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Integer(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Long
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateLong(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Long(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Float
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateFloat(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Float(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Double
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateDouble(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Double(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为Date，格式yyyy-MM-dd
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateDate(String value) {
		return validateDate(value, "yyyy-MM-dd");
	}

	/**
	 * 验证是否为Date，格式yyyy-MM-dd HH:mm:ss
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateTime(String value) {
		return validateDate(value, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 验证是否为Boolean
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateBoolean(String value) {
		if (value == null || value.equals(""))
			return false;
		try {
			new Boolean(value);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 验证是否为空
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateRequired(String value) {
		if (value == null || value.equals(""))
			return false;
		else
			return true;
	}

	/**
	 * 验证最大长度
	 * 
	 * @param value
	 * @param length
	 * @return
	 */
	public static boolean validateMaxLength(String value, int length) {
		if (value == null)
			return false;
		if (value.length() > length)
			return false;
		return true;
	}

	/**
	 * 根据正则表达式验证
	 * 
	 * @param value
	 * @param pattern
	 * @return
	 */
	public static boolean validateMask(String value, String pattern) {
		if (value == null)
			return false;
		Pattern pt = Pattern.compile(pattern);
		return pt.matcher(value).matches();
	}

	/**
	 * 验证日期
	 * 
	 * @param pattern
	 * @param string
	 * @return
	 */
	public static boolean validateDate(String value, String pattern) {
		if (value == null || value.equals(""))
			return false;
		if (value.length() != pattern.length())
			return false;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		format.setLenient(false);
		try {

			format.parse(value);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	// 对前后没有引号的字符串添加引号
	public static String Addquotes(String str) {
		if (str != null) {
			if (!str.startsWith("'"))
				return quotedStr(str);
			else
				return str;
		} else
			return "''";
	}

	/**
	 * 将字符串用引号括起来,适用于SQL拼装
	 * 
	 * @param str
	 * @return
	 */
	public static String quotedStr(String str) {
		if (str != null)
			return "'".concat(str).concat("'");
		else
			return "''";
	}

	public static void main(String[] args) {
		System.out.println(quotedStr(""));
	}

	/**
	 * @param conn
	 * @param stat
	 * @param rs
	 * @throws SQLException
	 *             关闭数据库资源
	 */
	public static void closeDataBaseResource(Connection conn, Statement stat,
			ResultSet rs) throws Exception {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stat != null) {
				stat.close();
				stat = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}

	}

	public static int getModelFieldSize(Object obj) throws Exception {
		if (obj == null) {
			logger.error("Object is null!");
			return 0;
		}
		int l = 0;
		if ((obj instanceof Class[]) || (obj instanceof Class[])) {
			Class[] clss = null;

			if (obj instanceof Class[])
				clss = (Class[]) obj;
			else if (obj instanceof Object[]) {
				Object[] objs = (Object[]) obj;
				clss = new Class[objs.length];
				for (int i = 0; i < objs.length; i++)
					clss[i] = objs[i].getClass();
			}

			for (int i = 0; i < clss.length; i++)
				l = l + getModelFieldSize(clss[i]);
			return l;
		}

		if (obj instanceof Map)
			return ((Map) obj).size();

		Class cls;
		if (obj instanceof Class)
			cls = (Class) obj;
		else
			cls = obj.getClass();
		Field fieldlist[] = cls.getDeclaredFields();
		if (fieldlist.length <= 0) {
			// err("对象:[" + cls.getName() + "]字段为空!");
			return 0;
		}
		for (int i = 0; i < fieldlist.length; i++) {
			// if (fieldlist[i].getType().getSimpleName().equalsIgnoreCase(
			// "boolean"))
			// continue;
			String fTypeName = fieldlist[i].getType().getName();
			if (fTypeName.indexOf("com.ztkj") >= 0) {
				// System.out.println(fieldlist[i].getName());
				// System.out.println(fieldlist[i].getType());
				Field[] subfieldlist = fieldlist[i].getType()
						.getDeclaredFields();
				int il = subfieldlist.length;
				if (il > 0) {
					l = l + il;
					continue;
				}
			}
			l++;
		}
		// l = fieldlist.length;
		return l;
	}

	public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	public static Integer stringToInteger(String str) {
		if (null == str || "".equals(str.trim())) {
			return null;
		} else if (GlobalFun.validateInteger(str)) {
			return Integer.parseInt(str);
		} else {
			return null;
		}
	}

	public static Long stringToLong(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateLong(str)) {
			return Long.parseLong(str);
		} else {
			return null;
		}
	}

	public static Double stringToDouble(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateDouble(str)) {
			return Double.parseDouble(str);
		} else {
			return null;
		}
	}

	public static Float stringToFloat(String str) {
		if (str == null || "".equals(str)) {
			return null;
		} else if (GlobalFun.validateFloat(str)) {
			return Float.parseFloat(str);
		} else {
			return null;
		}
	}

	public static String numberToString(String str) {
		if (str == null) {
			return "";
		} else {
			return str.trim();
		}
	}

	public static String numberToString(Integer lg) {
		if (lg == null) {
			return "";
		} else {
			return lg + "";
		}
	}

	public static String numberToString(Long lg) {
		if (lg == null) {
			return "";
		} else {
			// try {
			// return
			// numberFormater.parse(numberFormater.format(lg).toString()).longValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			numberFormater.setGroupingUsed(false);
			return numberFormater.format(lg);
		}
	}

	public static String numberToString(Double db) {
		if (db == null) {
			return "";
		} else {
			numberFormater.setGroupingUsed(false);
			numberFormater.setMaximumFractionDigits(4);
			return numberFormater.format(db);
			// try {
			// return
			// numberFormater.parse(numberFormater.format(db).toString()).doubleValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// return numberFormater+"";
		}
	}

	public static String numberToString(Float db) {
		if (db == null) {
			return "";
		} else {
			numberFormater.setGroupingUsed(false);
			return numberFormater.format(db);
			// try {
			// return
			// numberFormater.parse(numberFormater.format(db).toString()).floatValue()+"";
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// return numberFormater+"";
		}
	}

	/**
	 * 判断一个字符串的类型 输入：判断字符串 返回： 如果字符串是数字，返回0， 如果字符串是字母，返回1， 如果字符串是汉字，返回2,
	 * 如果字符串为空,返回3 Author :yczyk
	 */
	public static int justAStrType(String sStr) {
		int iStart, result = 0;
		Boolean IsNumber = true, IsChar = true;
		int iLen = sStr.length();
		if (iLen == 0)
			result = 3;
		else {
			for (iStart = 0; iStart < iLen; iStart++) {
				if (IsNumber) {
					IsNumber = sStr.substring(iStart, iStart + 1).matches(
							"[0-9]");
					if (IsNumber)
						continue;
				}
				if (IsChar) {
					IsChar = sStr.substring(iStart, iStart + 1).matches(
							"[0-9a-zA-Z]");
					if (IsChar)
						continue;
				}
				if ((!IsNumber) && (!IsChar)) {
					result = 2;
					break;
				}
			}
			if (result != 2) {
				if ((IsNumber) && (IsChar))
					result = 0;
				else if (IsNumber)
					result = 0;
				else
					result = 1;
			}
		}
		return result;
	}

	public static double getTwopoint(double p) {
		try {
			return df.parse(df.format(p)).doubleValue();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 将字符串的引号去掉
	 * 
	 * @param str
	 * @return
	 */
	public static String subquotedStr(String str) {
		if (str == null) {
			return str;
		}
		return str.replace("'", "");
	}

	public static Integer disFormat(String preFix, String str) {
		if (!hasValue(str))
			return 0;
		int l = preFix.trim().length();
		if (l > str.length())
			return 0;
		String data = str.substring(l);
		Integer result = Integer.valueOf(data);
		return result;
	}

	public static String format(String preFix, Integer len, Integer number) {
		int l = len - preFix.trim().length();

		if (l > number.toString().length()) {
			return preFix + format(number, '0', l);
		} else {
			return preFix + number;
		}

	}

	public static String format(Integer number, char c, Integer len) {
		StringBuffer str = new StringBuffer();
		for (int i = 1; i <= len - number.toString().length(); i++)
			str.append(c);
		str.append(number);
		return str.toString();
	}

}
